<template>
  <el-container class="el-container" v-loading="loadingAll">
    <el-row style="width: 100%">
      <el-row style="margin-top: 20px">
        <el-col :span="2" :offset="22">
          <el-button type="primary" @click="pub">发布</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-table
          v-loading="loading"
          class="order-table"
          :data="tableData"
          border
          :header-cell-style="{background:'#ebecf0',color:'#000000',fontSize:'12px',fontWeight:'normal'}"
          style="width: 100%">
          <el-table-column
            prop="ticketID"
            label="项目名称"
            width="400">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="5">
                  <el-image class="detail-img" :src="scope.row.image"></el-image>
                </el-col>
                <el-col :span="19" style="padding-left: 10px">
                  <el-row>
                    <span class="span-name" @click="goEventPubDetail(scope.row)">{{ scope.row.eventName }}</span>
                  </el-row>
                  <el-row style="color: #999999; font-size: 12px">
                    <span>演出时间：</span><br/>{{ scope.row.startTime }} ~ {{ scope.row.endTime }}
                  </el-row>
                  <el-row style="color: #999999; font-size: 12px">
                    <span>演出场馆：</span>{{ scope.row.place }}号场馆
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            prop="eventDescr"
            label="描述"
            width="350px">
          </el-table-column>
          <el-table-column
            prop="lowPrice"
            label="抵挡价"
            align="center">
            <template slot-scope="scope">
              ￥ {{ toDecimal2(scope.row.lowPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="midPrice"
            label="中档价"
            align="center">
            <template slot-scope="scope">
              ￥ {{ toDecimal2(scope.row.midPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="highPrice"
            label="高档价"
            align="center">
            <template slot-scope="scope">
              ￥ {{ toDecimal2(scope.row.highPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="onSale"
            label="状态"
            align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.onSale === 1">开售</span>
              <span v-if="scope.row.onSale === 2">停售</span>
              <span v-if="scope.row.onSale === 3">已删除</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-button class="btn-front" type="info" size="mini" plain
                         v-if="isSaleDeadlineDate(scope.row.startTime) && scope.row.onSale === 1"
                         @click="sale(scope.row, 2)">停售
              </el-button>
              <el-button class="btn-front" type="info" size="mini" plain
                         v-if="isSaleDeadlineDate(scope.row.startTime) && scope.row.onSale === 2"
                         @click="sale(scope.row, 1)">开售
              </el-button>
              <el-button class="btn-front" v-if="scope.row.onSale !== 3" type="info" size="mini" plain @click="editEvent(scope.row)">编辑</el-button>
              <el-button class="btn-front" v-if="scope.row.onSale !== 3" type="danger" size="mini" plain @click="deleteEvent(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-pagination
          class="pagination"
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
          :page-size="pageSize">
        </el-pagination>
      </el-row>
    </el-row>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" style="margin-top: -70px">
      <el-form :model="form">
        <el-form-item label="海报" :label-width="formLabelWidth" align="left">
          <el-upload
            :action="upload.url"
            :headers="upload.headers"
            list-type="picture-card"
            accept="image/jpeg,image/jpg,image/png"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="attachmentSimples"
            :class="[uploadDisabled ? 'disabled' : '']"
            :limit="1"
            :on-change="handleLimit">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目名称" :label-width="formLabelWidth" align="left">
          <el-input v-model="form.eventName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="时间" :label-width="formLabelWidth" align="left">
          <el-date-picker
            v-model="datePickerValue"
            type="datetimerange"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目描述" :label-width="formLabelWidth" align="left">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入项目描述"
            v-model="form.eventDescr">
          </el-input>
        </el-form-item>
        <el-form-item label="抵挡票价" :label-width="formLabelWidth" align="left">
          ￥
          <el-input-number v-model="form.lowPrice" :precision="2" :step="0.01"
                           controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="中档票价" :label-width="formLabelWidth" align="left">
          ￥
          <el-input-number v-model="form.midPrice" :precision="2" :step="0.01" controls-position="right"/>
        </el-form-item>
        <el-form-item label="高档票价" :label-width="formLabelWidth" align="left">
          ￥
          <el-input-number v-model="form.highPrice" :precision="2" :step="0.01" controls-position="right"/>
        </el-form-item>
        <el-form-item label="场馆" :label-width="formLabelWidth" align="left">
          <el-select v-model="form.place" placeholder="请选择场馆">
            <el-option label="1号场馆" :value="1"></el-option>
            <el-option label="2号场馆" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" align="left">
          <el-radio-group v-model="form.onSale">
            <el-radio :label="1">开售</el-radio>
            <el-radio :label="2">停售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="imgDialogVisible" style="margin-top: -70px">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  name: 'EventPub',
  created () {
    this.getEvents()
  },
  data () {
    return {
      loadingAll: false,
      total: 10,
      pageSize: 5,
      curPage: 1,
      loading: false,
      tableData: [],
      dialogTitle: '',
      dialogFormVisible: false,
      dialogImageUrl: '',
      formLabelWidth: '100px',
      imgDialogVisible: false,
      uploadDisabled: false,
      upload: {
        url: '/api/upload',
        headers: {
          'token': this.getToken()
        }
      },
      attachmentSimples: [
        {
          url: ''
        }
      ],
      form: {
        eventName: '',
        startTime: '',
        endTime: '',
        lowPrice: '',
        midPrice: '',
        highPrice: '',
        eventDescr: '',
        image: '',
        place: '',
        onSale: true,
        userID: ''
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      datePickerValue: ''
    }
  },
  methods: {
    getEvents () {
      let _this = this
      _this.loading = true
      let getUrl = '/api/events?page=' + _this.curPage + '&pageSize=' + _this.pageSize + '&userID=' + _this.getUserID()
      this.$axios({
        url: getUrl,
        method: 'get',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': _this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          let resData = response.data.data
          _this.tableData = resData.rows
          _this.total = resData.total
          document.documentElement.scrollTop = 0
          _this.loading = false
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          this.err(response.data.msg)
        }
      })
    },
    handleCurrentChange (val) {
      this.curPage = val
      this.loading = true
      this.getEvents()
    },
    pub () {
      this.form = {
        eventName: '',
        startTime: '',
        endTime: '',
        lowPrice: '',
        midPrice: '',
        highPrice: '',
        eventDescr: '',
        image: '',
        place: '',
        onSale: 1,
        userID: ''
      }
      this.dialogFormVisible = true
      this.dialogTitle = '发布'
      this.attachmentSimples = []
      this.datePickerValue = ''
      this.handleLimit(null, this.attachmentSimples)
    },
    deleteEvent (row) {
      this.$confirm('您执行的是[ ' + row.eventName + ' ]票务删除操作。若此票务已有售出的票，系统将自动进行退款, 是否继续?', '票务删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除请求
        let _this = this
        _this.loadingAll = true
        _this.$axios({
          url: '/api/events/' + row.eventID,
          method: 'delete',
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'token': this.getToken()
          }
        }).then((response) => {
          if (response.data.code === 1) {
            _this.loadingAll = false
            _this.success('票务删除成功！')
            _this.getEvents()
          } else {
            _this.isTokenExpired(_this, response.data.msg)
            _this.err(response.data.msg)
          }
        })
      }).catch(() => {
        this.info('已取消删除')
      })
    },
    editEvent (row) {
      this.form = row
      this.dialogTitle = '编辑'
      this.attachmentSimples = [
        {
          url: row.image,
          name: 'image',
          id: 'id'
        }
      ]
      this.handleLimit(null, this.attachmentSimples)
      this.datePickerValue = [new Date(row.startTime), new Date(row.endTime)]
      this.dialogFormVisible = true
    },
    sale (row, onSale) {
      let url = '/api/events'
      if (onSale === 2) {
        url += '/haltsale?eventID=' + row.eventID
      } else if (onSale === 1) {
        url += '/onsale?eventID=' + row.eventID
      } else {
        return
      }
      let _this = this
      _this.loadingAll = true
      _this.$axios({
        url: url,
        method: 'put',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          _this.loadingAll = false
          _this.success('状态更新成功！')
          _this.getEvents()
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          _this.err(response.data.msg)
        }
      })
    },
    handleRemove (file, fileList) {
      this.handleLimit(null, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.imgDialogVisible = true
    },
    handleSuccess (rep, file, fileList) {
      if (rep.msg === '登录已失效，请重新登录') {
        this.$router.push({path: '/login'})
        this.err(rep.msg)
      }
      this.form.image = rep.data
      this.attachmentSimples.push({url: rep.data})
      console.log(this.attachmentSimples)
    },
    handleLimit (file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true
        this.$set(this, 'uploadDisabled', true)
      } else {
        this.uploadDisabled = false
        this.$set(this, 'uploadDisabled', false)
      }
      this.$forceUpdate()
    },
    goEventPubDetail (row) {
      let routeData = this.$router.resolve({
        name: 'EventPubDetail',
        params: {
          id: row.eventID
        },
        query: {
          title: row.eventName
        }
      })
      window.open(routeData.href, '_blank')
    },
    save () {
      let method = ''
      let msg = ''
      if (this.dialogTitle === '发布') {
        method = 'post'
        msg = '赛事发布成功！'
      }
      if (this.dialogTitle === '编辑') {
        method = 'put'
        msg = '赛事更新成功！'
      }
      this.form.startTime = this.formatData(this.datePickerValue[0])
      this.form.endTime = this.formatData(this.datePickerValue[1])
      this.form.userID = this.getUserID()
      let _this = this
      _this.loadingAll = true
      _this.$axios({
        url: '/api/events',
        method: method,
        data: JSON.stringify(_this.form),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          _this.success(msg)
          _this.getEvents()
          _this.dialogFormVisible = false
          _this.loadingAll = false
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          _this.err(response.data.msg)
        }
      })
    },
    cancel () {
      this.dialogFormVisible = false
    }
  }
}
</script>

<style scoped>
.el-container {
  width: 80%;
  margin: 0 auto;
}

.btn-front {
  margin-left: 10px;
  margin-bottom: 5px;
}

.detail-img {
  height: 111px;
  width: 82px;
}

.btn {
  margin-bottom: 5px;
}

.span-name:hover {
  cursor: pointer;
  color: var(--them-color);
}

.disabled {

.el-upload.el-upload--picture-card {
  display: none !important;
}

}

.disabled {

.el-button--success.is-plain {
  display: none !important;
}

}
</style>
